package com.ithe.orderandpay.interceptor;


import cn.hutool.json.JSONUtil;
import com.ithe.core.result.Result;
import com.ithe.user.api.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            Result result = Result.failed(ResultCode.CLIENT_AUTHENTICATION_FAILED);
            responseJson(response, JSONUtil.toJsonStr(result));
            return false;
        }

        //用户微服务中查询是否登录
        Result<User> resultVo = userFeignClient.queryUserByToken(token);
        User user=resultVo.getData();

        if(user==null){
            Result result = Result.failed(ResultCode.CLIENT_AUTHENTICATION_FAILED);
            responseJson(response, JSONUtil.toJsonStr(result));
            return false;
        }

        //把用户放入当前线程
        UserThreadLocal.set(user);

        return true;
    }


    public static void responseJson(HttpServletResponse response, String json) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        try {
            response.getWriter().write(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        //移除当前线程的用户
        UserThreadLocal.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
